package top.lingkang.mm.orm;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import top.lingkang.mm.error.MagicException;

import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * {@link QueryWrapper} 等查询前处理
 *
 * @author lingkang
 * Created by 2024/3/5
 */
public class MagicCreateLangDriver extends XMLLanguageDriver implements LanguageDriver {
    private final Field resultClass;

    public MagicCreateLangDriver() {
        try {
            resultClass = ResultMap.class.getDeclaredField("type");
            resultClass.setAccessible(true);
        } catch (NoSuchFieldException e) {
            throw new MagicException("MagicLanguageDriver 初始化失败", e);
        }
    }

    @Override
    public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
        if (mappedStatement.getSqlCommandType() == SqlCommandType.SELECT) {
            try {
                // 设置类型
                HashMap<String, Object> map = (HashMap<String, Object>) parameterObject;
                ResultMap resultMap = mappedStatement.getResultMaps().get(0);
                resultClass.set(resultMap, map.get("resType_"));
            } catch (Exception e) {
                throw new MagicException(e);
            }
        }
        return super.createParameterHandler(mappedStatement, parameterObject, boundSql);
    }
}
